<template>
  <CDialog
    :title="title"
    v-model:visible="dialogVisible"
    :loading="loading"
    confirmText="保存"
    cancelText="关闭"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
  >
    <el-form ref="formRef" :model="formState" :rules="rules" label-position="top">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="物料名称" prop="nodeName">
            <el-input v-model="formState.nodeName" type="text" placeholder="请输入" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料编码" prop="nodeCode">
            <el-input v-model="formState.nodeCode" type="text" placeholder="请输入" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="材料类别或牌号">
            <el-input
              v-model="formState.materialCategory"
              type="text"
              placeholder="请输入"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用量" prop="dosage">
            <CDosageAndUnit
              v-model:dosage="formState.dosage"
              v-model:unit="formState.unit"
              :digit="9"
              is-group
            ></CDosageAndUnit>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="formState.remark" type="textarea" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </CDialog>
</template>

<script lang="ts" setup name="MaterialDialog">
import { withDefaults, defineProps, defineEmits, computed, watch, reactive, ref } from 'vue';
import { CDialog } from '@/components/CDialog';
import CDosageAndUnit from '@/businessComponents/CDosageAndUnit/index.vue';
import type { GetListBomTreeResult } from '@/apis/pcf/myModel/model/modelDetailModel';
import { useMessage } from '@/hooks/useMessage';
import { MaterialDialogOperationType } from './material-dialog';
import { rules } from './rules';
import { createBom, updateBom } from '@/apis/todo/flowBusiness';

interface MaterialDialogProps {
  visible: boolean;
  formNo: string;
  nodeItem?: GetListBomTreeResult;
}
const props = withDefaults(defineProps<MaterialDialogProps>(), {});
const emits = defineEmits(['update:visible', 'refresh']);

const { createMessage } = useMessage();
const dialogVisible = computed({
  get: () => {
    return props.visible;
  },
  set: (value: boolean) => {
    emits('update:visible', value);
  }
});
watch(
  () => dialogVisible.value,
  val => {
    if (val) {
      init();
    } else {
      formRef.value?.resetFields();
    }
  }
);

const formRef = ref();
const loading = ref(false);
/**
 * 表单内容
 */
const formState = reactive({
  quantity: 1,
  nodeName: '',
  nodeCode: '',
  materialCategory: '',
  dosage: null as any,
  unit: 'kg',
  remark: ''
});

/**
 * 操作类型
 */
const operationType = ref<MaterialDialogOperationType>();

/**
 * 弹窗标题
 */
const title = computed(() => {
  return operationType.value === 'ADD' ? '新增物料信息' : '编辑物料信息';
});

/**
 * 初始化
 */
function init() {
  loading.value = false;
  if (!props.nodeItem) {
    operationType.value = 'ADD';
    formState.quantity = 1;
    formState.nodeName = '';
    formState.nodeCode = '';
    formState.materialCategory = '';
    formState.unit = 'kg';
    formState.remark = '';
    formState.dosage = '';
  } else {
    operationType.value = 'EDIT';
    getData(props.nodeItem);
  }
}

/**
 * 获取节点详情
 */
async function getData(res: any) {
  formState.quantity = res.quantity;
  formState.nodeName = res.nodeName;
  formState.nodeCode = res.nodeCode;
  formState.materialCategory = res.materialCategory;
  res.unit && (formState.unit = res.unit);
  if (res.unit == 'pcs') {
    // formState.dosage = '1';
    formState.dosage = res.dosage;
  } else {
    formState.dosage = res.dosage;
  }
  formState.remark = res.remark;
}

/**
 * 保存按钮
 */
function handleConfirm() {
  console.log('handleConfirm');
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      handleEditNodeReq();
    }
  });
}

/**
 * 实际修改请求提交
 */
async function handleEditNodeReq() {
  try {
    loading.value = true;
    const params = {
      ...formState,
      nodeNo: props.nodeItem ? props.nodeItem.nodeNo : undefined,
      formNo: props.formNo,
      dosage: formState.dosage
    };
    if (operationType.value === 'ADD') {
      await createBom(params);
    } else {
      // 编辑接口
      await updateBom(params);
    }
    createMessage.success(operationType.value === 'ADD' ? '新增成功！' : '编辑成功！');
    emits('refresh');
    dialogVisible.value = false;
  } catch (error) {
    console.log('error', error);
    loading.value = false;
  }
}
</script>
